package org.unt.menu;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Menu {

	private Map<String, Link> map = new HashMap<String, Link>();

	private List<Link> links = new ArrayList<Link>();

	private Link markedLink;

	public Menu() {

		links.add(new Link("aaa", "aaa.action", 0, true));
		links.add(new Link("aa1", "aa1.action", 1, false));
		links.add(new Link("a11", "a11.action", 2, false));
		links.add(new Link("a12", "a12.action", 2, false));
		links.add(new Link("aa2", "aa2.action", 1, false));
		links.add(new Link("bbb", "bbb.action", 0, false));
		links.add(new Link("ccc", "ccc.action", 0, false));
		links.add(new Link("cc1", "cc1.action", 1, false));
		links.add(new Link("cc2", "cc2.action", 1, false));
		links.add(new Link("ddd", "ddd.action", 0, false));

		for (Link link : links) {
			map.put(link.getUrl(), link);
		}

		markedLink = links.get(0);
	}

	public List<Link> entriesForDisplay(String url) {

		markedLink.setMarked(false);
		markedLink = map.get(url);

		if (markedLink == null)
			throw new RuntimeException("Exception : It does not exist a menu entry for this url " + url);

		markedLink.setMarked(true);

		List<Link> entriesForDisplay = new ArrayList<Link>();
		int rest = links.size(); // For taking the level 0 links after the level 0 group marked

		for (int i = 0; i < links.size(); i++) {

			if (links.get(i).isMarked()) {

				int level = links.get(i).getLevel();

				List<Link> invertedList = new ArrayList<Link>();
				int j = i;
				while (true) {

					j--;
					if (j == -1 || links.get(j).getLevel() == 0) {
						break;
					}

					if (links.get(j).getLevel() == level) {

						invertedList.add(links.get(j));

					} else if (links.get(j).getLevel() < level) {

						invertedList.add(links.get(j));

						level--;
						if (level == 0)
							break;
					}
				}

				Collections.reverse(invertedList);
				entriesForDisplay.addAll(invertedList);

				rest = i + 1;
				entriesForDisplay.add(links.get(i));

				for (int k = i + 1; k < links.size(); k++) {

					if (links.get(k).getLevel() == links.get(i).getLevel()) {
						entriesForDisplay.add(links.get(k));
					} else {
						rest = k + 1;
						break;
					}
				}

				break;
			}

			if (links.get(i).getLevel() == 0) { // Add link only if it is level 0
				entriesForDisplay.add(links.get(i));
			}
		}

		for (; rest < links.size(); rest++) {
			if (links.get(rest).getLevel() == 0) {
				entriesForDisplay.add(links.get(rest));
			}
		}

		return entriesForDisplay;
	}

	public static String asStringForTest(List<Link> links) {

		StringBuffer buf = new StringBuffer();

		for (Link link : links) {
			buf.append(link.toStringForTest() + "\n");
		}

		return buf.toString();
	}
}
